﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace Roton
{
    class EventTimer : IDisposable
    {
        public event EventHandler Tick;

        double executionFrequency;
        Thread executionThread;

        public EventTimer(double freq)
        {
            executionFrequency = freq;
            executionThread = new Thread(new ThreadStart(ExecutionThreadFunction));
            executionThread.Start();
        }

        void ExecutionThreadFunction()
        {
            Stopwatch sw = new Stopwatch();
            long swInterval = (long)((double)Stopwatch.Frequency / executionFrequency);
            long swLast = sw.ElapsedTicks;
            sw.Start();

            while (true)
            {
                long swSnapshot = sw.ElapsedTicks;
                while (swSnapshot - swLast >= swInterval)
                {
                    swLast += swInterval;
                    if (Tick != null)
                        Tick(this, EventArgs.Empty);
                }
                Thread.Sleep(1);
            }
        }

        public void Dispose()
        {
            executionThread.Abort();
        }
    }
}
